package com.solution.admin.report.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.solution.common.controller.BaseController;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils_add;
import com.solution.common.utils.string.StringUtil;
import com.solution.wx.share.entity.ShareProductStatisticsEntity;
import com.solution.wx.share.service.ShareInfoService;
import com.solution.wx.share.service.ShareProductStatisticsService;

/**
 * 分享信息统计
 * @author xkl
 * @date 2018年5月21日 下午4:00:04
 */
@RequestMapping("/share")
@Controller
public class ShareInfoController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(BaseController.class);

	@Autowired
	private ShareInfoService shareInfoService;
	
	@Autowired
	private ShareProductStatisticsService shareProductStatisticsService;
	
	/**
	 * 跳转至商品分享统计页面
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月21日 下午5:23:06
	 */
	@RequestMapping("/toShareProdcutPage")
	public String toShareProductPage(HttpServletRequest request){
		return "share/share_product_list";
	}
	
	/**
	 * 查询商品统计信息
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月21日 下午4:33:21
	 */
	@RequestMapping("/listShareProductPage")
	@ResponseBody
	public Map<String, Object> listShareProductPage(HttpServletRequest request){
		//返回值
		Map<String,Object> result = new HashMap<String, Object>();
		//参数
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		String productName = request.getParameter("productName");
		String productCode = request.getParameter("productCode");
		//调整排序时不返回第一页
		String isSort = request.getParameter("isSort");
		String currentPage = request.getParameter("currentPage");
		if ("true".equals(isSort)) {
			pageParam.setPageNum(Integer.parseInt(currentPage));
		}
		//组装排序参数
		List<String> orderByList = new ArrayList<String>();
		if (StringUtil.isNotNull(request.getParameter("shareSort"))) {
			orderByList.add("SHARE_QUANTITY "+request.getParameter("shareSort"));
			result.put("shareSort", request.getParameter("shareSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("pvViewSotr"))) {
			orderByList.add("PV_VIEW_QUANTITY "+request.getParameter("pvViewSotr"));
			result.put("pvViewSotr", request.getParameter("pvViewSotr"));
		}
		if (StringUtil.isNotNull(request.getParameter("uvViewSort"))) {
			orderByList.add("UV_VIEW_QUANTITY "+request.getParameter("uvViewSort"));
			result.put("uvViewSort", request.getParameter("uvViewSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("orderNumSort"))) {
			orderByList.add("SHARE_ORDER_NUM "+request.getParameter("orderNumSort"));
			result.put("orderNumSort", request.getParameter("orderNumSort"));
		}
		if (StringUtil.isNotNull(request.getParameter("totalMoneySort"))) {
			orderByList.add("SHARE_TOTAL_MONEY "+request.getParameter("totalMoneySort"));
			result.put("totalMoneySort", request.getParameter("totalMoneySort"));
		}
		//组装条件参数
		Map<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("productName", productName);
		paramMap.put("productCode", productCode);
		paramMap.put("orderByList", orderByList);
		try {
			PageBean pageBean = shareProductStatisticsService.listPage(pageParam, paramMap);
			result.put("pageBean", pageBean);
			result.put("rows", pageBean.getRecordList());
			result.put("total", pageBean.getTotalCount());
			result.put("productName", productName);
			result.put("productCode", productCode);
			result.put("currentPage", pageBean.getCurrentPage());
		} catch (Exception e) {
			handleException("查询分享统计信息失败", logger, e);
		}
		return result;
	}
	
	/**
	 * 跳转至商品分享统计详情页面
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年5月21日 下午5:23:06
	 */
	@RequestMapping("/toDetailPage")
	public String toDetailPage(HttpServletRequest request){
		long id = Long.valueOf(request.getParameter("id"));
		try {
			String startTime = DateUtils_add.formatDate(
					DateUtils_add.getMonthStart(new Date()), DateUtils_add.DATE_FORMAT_DATEONLY);
			String endTime = DateUtils_add.formatDate(
					DateUtils_add.getMonthEnd(new Date()), DateUtils_add.DATE_FORMAT_DATEONLY);
			Long diffDays = DateUtils_add.getDateDiff(startTime, endTime);
			ShareProductStatisticsEntity staticEntity = shareProductStatisticsService.getById(id);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("productId", staticEntity.getProductId());
			paramMap.put("startTime", startTime);
			paramMap.put("endTime", endTime);
			ShareProductStatisticsEntity dalyStatics = shareProductStatisticsService.getDailyStatisBy(paramMap);
			request.setAttribute("dalyStatics", dalyStatics);
			request.setAttribute("staticEntity", staticEntity);
			request.setAttribute("startTime", startTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("diffDays", diffDays.intValue()+1);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "share/share_product_detail";
	}

	/**
	 * 跳转至统计详情
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年6月20日 下午6:34:27
	 */
	@RequestMapping(value = "/listDetailPage")
	@ResponseBody
	public Map<String, Object> listDetailPage(HttpServletRequest request) {
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		long productId = Long.valueOf(request.getParameter("productId"));
		String partTime = request.getParameter("partTime");
		String[] dates = {};
		if (StringUtil.isNotNull(partTime) && partTime.indexOf(" - ") > 0) {
			dates = partTime.split(" - ");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("productId", productId);
			if(StringUtil.isNotNull(dates[0]) && StringUtil.isNotNull(dates[1])) {
				paramMap.put("startTime", dates[0] + " 00:00:00");
				paramMap.put("endTime", dates[1] + " 23:59:59");
			}
			//计算天数
			resultMap.put("startTime", dates[0]);
			resultMap.put("endTime", dates[1]);
			Long diffDays = DateUtils_add.getDateDiff(dates[0] + " 00:00:00", dates[1] + " 23:59:59");
			resultMap.put("diffDays", diffDays.intValue()+1);
			
			//统计该时间段内数据量
			ShareProductStatisticsEntity dalyStatics = shareProductStatisticsService.getDailyStatisBy(paramMap);
			resultMap.put("dalyStatics", dalyStatics);
			
			//查询列表数据
			PageBean dailyPage = shareProductStatisticsService.listDailyPage(pageParam, paramMap);
			resultMap.put("rows", dailyPage.getRecordList());
			resultMap.put("total", dailyPage.getTotalCount());
			resultMap.put("code", 1);
			resultMap.put("msg", "查询成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 查询每日统计折线图数据
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年6月22日 上午11:51:37
	 */
	@RequestMapping("/queryDailyData")
	@ResponseBody
	public Map<String, Object> queryDailyData(HttpServletRequest request) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("productId", request.getParameter("productId"));
		String partTime = request.getParameter("partTime");
		String[] dates = {};
		if (StringUtil.isNotNull(partTime) && partTime.indexOf(" - ") > 0) {
			dates = partTime.split(" - ");
		}
		if(StringUtil.isNotNull(dates[0]) && StringUtil.isNotNull(dates[1])) {
			paramMap.put("startTime", dates[0] + " 00:00:00");
			paramMap.put("endTime", dates[1] + " 23:59:59");
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			//查询图表数据
			Map<String, Object> dailyData = shareProductStatisticsService.queryDailyData(paramMap);
			String[] allDate = 
					DateUtils_add.getDateBetweenStartToEnd(dates[0] + " 00:00:00", dates[1] + " 23:59:59", "yyyy-MM-dd");
			String[] allDateShow = 
					DateUtils_add.getDateBetweenStartToEnd(dates[0] + " 00:00:00", dates[1] + " 23:59:59", "MM月dd日");
			
			List<String> shareLine = new ArrayList<String>();	//分享折线
			List<String> pvLine = new ArrayList<String>();		//PV折线
			List<String> registerLine = new ArrayList<String>();//新增用户折线
			List<String> salesNumLine = new ArrayList<String>();//销量折线
			List<String> salesMoneyLine = new ArrayList<String>();//销售额折线
			for (int i=0; i<allDate.length; i++) {
				String date = allDate[i];
				if(dailyData.containsKey(date)){
					JSONObject json = JSON.parseObject(JSON.toJSONString(dailyData.get(date)));
					shareLine.add(json.getString("shareQuantity"));
					pvLine.add(json.getString("pvViewQuantity"));
					registerLine.add(json.getString("registerQuantity"));
					salesNumLine.add(json.getString("shareOrderNum"));
					salesMoneyLine.add(json.getString("shareTotalMoney"));
				} else {
					shareLine.add("0");
					pvLine.add("0");
					registerLine.add("0");
					salesNumLine.add("0");
					salesMoneyLine.add("0");
				}
			}
			resultMap.put("allDate", allDate);
			resultMap.put("allDateShow", allDateShow);
			resultMap.put("shareLine", shareLine);
			resultMap.put("pvLine", pvLine);
			resultMap.put("registerLine", registerLine);
			resultMap.put("salesNumLine", salesNumLine);
			resultMap.put("salesMoneyLine", salesMoneyLine);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
}
